﻿using Sidvall.Net;
using Sidvall.Security;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Sidvall.Test
{
    class Program
    {
        #region Main

        static void Main(string[] args)
        {
            try
            {
                RegisterTypes();

                Sidvall.SystemContext.Current.CacheManager.Add("a", 1, null, System.TimeSpan.MinValue);
                Sidvall.SystemContext.Current.CacheManager.Add("a", 2, null, System.TimeSpan.MinValue);

                System.Console.WriteLine("Done.");
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(Sidvall.SystemContext.Current.SystemExceptionManager.GetMessage(ex));
            }
            System.Console.ReadLine();
        }

        #endregion

        #region DoTask

        private static async Task<string> DoTask(string name)
        {
            await Task.Delay(2000).ConfigureAwait(false);
            return name;
        }

        #endregion

        #region GetNamespace

        private static string GetNamespace(string schemaFileUrl)
        {
            return schemaFileUrl.Replace("http://", "").Replace("/", ".");
        }

        #endregion
        #region GetStream

        private static System.IO.Stream GetStream()
        {
            return null;
        }

        #endregion
        #region NextStartIndex

        private static int NextStartIndex(string text, string tag, int startIndex)
        {
            int index;

            if (startIndex > 0)
            {
                index = text.IndexOf(@"<" + tag, startIndex, System.StringComparison.OrdinalIgnoreCase);
                if (index < 0)
                {
                    index = text.IndexOf(@":" + tag, startIndex, System.StringComparison.OrdinalIgnoreCase);
                }
                if (index < 0)
                {
                    index = text.IndexOf(@"&lt;" + tag, startIndex, System.StringComparison.OrdinalIgnoreCase);
                }
            }
            else
            {
                index = text.IndexOf(@"<" + tag, System.StringComparison.OrdinalIgnoreCase);
                if (index < 0)
                {
                    index = text.IndexOf(@":" + tag, System.StringComparison.OrdinalIgnoreCase);
                }
                if (index < 0)
                {
                    index = text.IndexOf(@"&lt;" + tag, System.StringComparison.OrdinalIgnoreCase);
                }
            }
            return index;
        }

        #endregion
        #region GenerateCode

        private static void GenerateCode()
        {
            //// Create domain model from edmx file
            //var m = Sidvall.CodeGenerator.EdmxHelper.NewDomainModel("Model.edmx");
            //// Create domain model from resource file
            //var m = Sidvall.CodeGenerator.ResourceFileHelper.NewDomainModel("Resources.resx", "en-US");
            //// Create domain model from xsd files (NOT FINISHED)
            //var m = Sidvall.CodeGenerator.XsdHelper.NewDomainModel("Model.xsd");
            //// Generate Business Layer
            //this.RenderResourceLayer(m, @"XXX\GeneratedCode\Data");
            //this.RenderBusinessLayer(m, @"XXX\GeneratedCode");
            //// Generate Data Layer
            //this.RenderBusinessLayerDataPortalLocal(m, @"XXX\GeneratedCode");
            //this.RenderDataLayer(m, @"XXX.Data.Entity\GeneratedCode");
            //// Generate Web API Layer
            //this.RenderBusinessLayerServicesController(m, @"XXX.Web\GeneratedCode\Controllers\Api");
            //// Generate Portable REST Client
            //this.RenderBusinessLayerDataPortalRemote(m, @"XXX\GeneratedCode");
            //// Generate JavaScript REST Client
            //this.RenderWebLayer(m, @"XXX.Web\GeneratedCode\Scripts");
            //this.RenderWebLayerBO(m, @"XXX.Web\GeneratedCode\Scripts");
            //this.RenderWebLayerDataPortal(m, @"XXX.Web\GeneratedCode\Scripts");
            //// Generate Web Client Resource File
            //this.RenderWebLayerResources(m, @"\XXX.Web\GeneratedCode");
        }

        #endregion
        #region FrameworkCode

        private static async System.Threading.Tasks.Task FrameworkCode()
        {
            // File Management - requires Sidvall.IO
            var files = Sidvall.SystemContext.Current.SystemStorageManager.GetFilesAsync(@"c:\", null, Sidvall.IO.SearchOption.AllDirectories, true);
            // Mail Management - requires Sidvall.Net.Mail
            await Sidvall.SystemContext.Current.SmtpClientManager.SendAsync(new string[] { "mailaddress1" }, "Subject", "Body", false);
            // SMS Management - requires Sidvall.Net.Sms
            await Sidvall.SystemContext.Current.SmsClientManager.SendAsync("00000000", "Hello!", false);
            // Serialization
            var json = Sidvall.Serialization.SerializerManager.Current.SerializeObject(files);
            // Global Cache
            Sidvall.SystemContext.Current.CacheManager.AddOrUpdate("key", 5, "region", new System.TimeSpan(1000));
            // REST client - requires Sidvall.Net
            var restClient = Sidvall.SystemContext.Current.HttpClientFactory.GetHttpClient(new HttpClientSettings());
            var response = await restClient.GetAsync("url");
            // SOAP client - requires Sidvall.Net
            var soapClient = Sidvall.SystemContext.Current.SoapClientFactory.GetSoapClient(new SoapClientSettings());
            response = await soapClient.SendSoapAsync("url", "content", "action");
            // Transaction - requires Sidvall.Data/Sidvall.Data.Sqlite
            using (var transaction = Sidvall.SystemContext.Current.TransactionScopeFactory.GetTransactionScope())
            {
                transaction.Complete();
            }
            // Authentication - requires Sidvall.Security.Authentication
            var authenticationClient = Sidvall.SystemContext.Current.AuthenticationManager.GetAuthenticationClient("STS address");
            var token = await authenticationClient.RequestResourceOwnerPasswordAsync("username", "password");
            // Log on dialog
            var authorizeResponse = Sidvall.UI.SystemContext.Current.DialogManager.LogOnAsync("STS address", "ClientId", "response type", "scopes", "ClientRedirectAddress",
                 TwoFactorProvider.None, null);
            // Authorization
            var principal = Sidvall.SystemContext.Current.PrincipalManager.CurrentPrincipal;
            var isAuthorized = Sidvall.SystemContext.Current.AuthorizationManager.IsAuthorized(principal, "resource", "action");
            isAuthorized = await Sidvall.SystemContext.Current.AuthorizationManager.IsAuthorizedAsync(principal, "resource", "action", null, "resource item id");
            // Logging
            await Sidvall.SystemContext.Current.LogManager.WriteAsync("info", "Message", Sidvall.Logging.LogCategories.WebApi, Sidvall.Logging.EventType.Information);
            // Settings
            var setting = Sidvall.SystemContext.Current.SettingsManager.GetSetting("TestSetting");
            // Resources
            var resource = Sidvall.SystemContext.Current.ResourceManager.GetString("TestResource");
        }

        #endregion
        #region RegisterTypes

        private static void RegisterTypes()
        {
            // Framework
            var authorizationProvider = new Sidvall.Security.PublicAuthorizationProvider();
            Sidvall.SystemContext.Current = new Sidvall.SystemContext()
            {
                AccountManager = new Sidvall.Security.AccountManager(null),
                AuthorizationManager = new Sidvall.Security.AuthorizationManager(authorizationProvider),
                AuthenticationManager = new Sidvall.Security.AuthenticationManager(new Sidvall.Security.AuthenticationProvider()),
                AuthenticationStrategyManager = new Sidvall.Security.AuthenticationStrategyManager(new Sidvall.Security.AuthenticationStrategy()
                {
                    AuthorityTokenEndpoint = "",
                    ClientId = "",
                    ClientSecret = "",
                }),
                CacheManager = new Sidvall.Caching.CacheManager(new Sidvall.Caching.MemoryCache()),
                ClaimManager = new Sidvall.Security.ClaimManager(new Sidvall.Security.ClaimsPrincipalManager()),
                CodeManager = new Sidvall.Reflection.CodeManager(new Sidvall.Reflection.Code()),
                UserExceptionManager = new Sidvall.ExceptionHandling.ExceptionManager(new Sidvall.ExceptionHandling.UserExceptionProvider()),
                SystemExceptionManager = new Sidvall.ExceptionHandling.ExceptionManager(new Sidvall.ExceptionHandling.SystemExceptionProvider()),
                HttpClientFactory = new Sidvall.Net.HttpClientFactory(),
                LauncherManager = new Sidvall.SystemEnvironment.LauncherManager(new Sidvall.SystemEnvironment.Windows.Launcher()),
                LogManager = new Sidvall.Logging.LogManager(new Sidvall.Logging.LogCollection()),
                PackageManager = new Sidvall.SystemEnvironment.PackageManager(new Sidvall.SystemEnvironment.Windows.Package()),
                SmtpClientManager = new Sidvall.Net.Mail.SmtpClientManager(new Sidvall.Net.Mail.SmtpClient()),
                SmsClientManager = new Sidvall.Net.Sms.SmsClientManager(new Sidvall.Net.Sms.SmsClient("")),
                SoapClientFactory = new Sidvall.Net.SoapClientFactory(),
                SqlManager = new Sidvall.Data.SqlManager(new Sidvall.Data.SqlServerProvider()),
                SystemStorageManager = new Sidvall.IO.StorageManager(new Sidvall.IO.FileSystem()),
                TransactionScopeFactory = new Sidvall.Data.TransactionScopeFactory(),
                TypeCache = new Sidvall.Reflection.TypeCache(),
                UserManager = new Sidvall.Security.UserManager(authorizationProvider),
                UserResponseStrategyManager = new Sidvall.Security.UserResponseStrategyManager(new Sidvall.Security.UserResponseStrategy()),
                UserStorageManager = new Sidvall.IO.StorageManager(new Sidvall.IO.FileSystem(Sidvall.IO.FolderType.MyPictures)),
                ZipFileFactory = new Sidvall.IO.Compression.ZipFileFactory(),

                // Client
                PrincipalContextManager = new Sidvall.Security.PrincipalContextManager(new Sidvall.Security.PrincipalContextProvider()),
                PrincipalManager = new Sidvall.Security.PrincipalManager(new Sidvall.Security.PrincipalProvider()),

                // Host specific
                CultureManager = new Globalization.CultureManager(new Sidvall.UI.Wpf.Globalization.CultureProvider()),
                ResourceManager = new Sidvall.Resources.ResourceManager(new Sidvall.Resources.ResourceProvider()),
                SettingsManager = new Sidvall.Configuration.SettingsManager(new Sidvall.Test.Configuration.ApplicationSettings()),
            };
            Sidvall.Data.Sqlite.SystemContext.Current = new Sidvall.Data.Sqlite.SystemContext()
            {
                SQLitePlatform = new SQLite.Net.Platform.Win32.SQLitePlatformWin32(),
            };
            Sidvall.Office.SystemContext.Current = new Sidvall.Office.SystemContext()
            {
                //ExcelManager = new Sidvall.Office.ExcelManager(new Sidvall.Office.Excel()),
            };
            Sidvall.Reporting.SystemContext.Current = new Sidvall.Reporting.SystemContext()
            {
                //ReportManager = new Sidvall.Reporting.ReportManager(new Sidvall.Reporting.Report()),
            };
            Sidvall.UI.SystemContext.Current = new Sidvall.UI.SystemContext()
            {
                ApplicationManager = new Sidvall.UI.ApplicationManager(),
                ConfigurationContext = new Sidvall.UI.Configuration.ConfigurationContext(new Sidvall.UI.Wpf.Views.ContentControlRegionManager()),
                DialogManager = new Sidvall.UI.Dialogs.DialogManager(
                    new Sidvall.UI.Wpf.Dialogs.FileDialog(),
                    new Sidvall.UI.Wpf.Dialogs.FolderDialog(),
                    new Sidvall.UI.Wpf.Dialogs.MessageDialogManager(),
                    new Sidvall.UI.Wpf.Dialogs.MessageBoxDialog(),
                    new Sidvall.UI.Wpf.Dialogs.WebSecurityDialogManager(),
                    new Sidvall.UI.Wpf.Dialogs.ProgressDialogManager(),
                    new Sidvall.UI.Wpf.Dialogs.WebDialogManager()),
                NavigationManager = new Sidvall.UI.Navigation.NavigationManager(),
            };
        }

        #endregion
    }
}
